package com.hro.rickpimines.project4.vogelspot1;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.os.Bundle;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class VogelOnMapsActivity extends MapActivity implements
        LocationListener
{

	MapController myMapController;

	public static final String TAG = "VogelOnMapsActivity";
	public Bitmap bmImg;
	private MapView mapView;

	@Override
	protected boolean isRouteDisplayed()
	{

		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vogelonmapsactivity);

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		MapController mapController = mapView.getController();
		mapController.setZoom(10);

		myMapController = mapView.getController();

		for (String s : getFiles()) {
			downloadFile(s);
		}

		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		Criteria criteria = new Criteria();
		String provider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(provider);

		// Initialize the location fields
		if (location != null) {

		} else {

		}
	}

	private String[] getFiles()
	{
		String result = null;
		InputStream is = null;
		StringBuilder sb = null;

		// http post
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
			        "http://vogelapp.rickheere.nl/viewer.php");

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection" + e.toString());
		}

		// convert response to string
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
			        is, "iso-8859-1"), 8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line = "0";

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			is.close();
			result = sb.toString();

		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		Log.v(TAG, "Files: " + result);
		return result.split("::");
	}

	void downloadFile(String fileUrl)
	{
		URL myFileUrl = null;
		try {
			myFileUrl = new URL(fileUrl);

			HttpURLConnection conn = (HttpURLConnection) myFileUrl
			        .openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();

			File tempDir = getCacheDir();
			
			String localFilePath = tempDir.getAbsolutePath() + "foto.jpg";
			
			FileOutputStream fos = new FileOutputStream(localFilePath, false);
			OutputStream os = new BufferedOutputStream(fos);

			byte[] buffer = new byte[1024];
			int byteRead = 0;

			while ((byteRead = is.read(buffer)) != -1) {
				os.write(buffer, 0, byteRead);
			}
			
			class FlushedInputStream extends FilterInputStream {
			    public FlushedInputStream(InputStream inputStream) {
			        super(inputStream);
			    }

			    @Override
			    public long skip(long n) throws IOException {
			        long totalBytesSkipped = 0L;
			        while (totalBytesSkipped < n) {
			            long bytesSkipped = in.skip(n - totalBytesSkipped);
			            if (bytesSkipped == 0L) {
			                int b = read();
			                if (b < 0) {
			                    break;  // we reached EOF
			                } else {
			                    bytesSkipped = 1; // we read one byte
			                }
			            }
			            totalBytesSkipped += bytesSkipped;
			        }
			        return totalBytesSkipped;
			    }
			}
			
			Bitmap photo = BitmapFactory.decodeStream(new FlushedInputStream(conn.getInputStream()));
			fos.close();
			
			ExifInterface exif = new ExifInterface(localFilePath);

			String latDMS = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
			String lngDMS = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
			String naam = exif.getAttribute(ExifInterface.TAG_MAKE);

			Log.v(TAG, "naam: " + naam);
			Log.v(TAG, "latDMS: " + latDMS + ", lngDMS: " + lngDMS);
			Log.v(TAG, "latDD: " + DMStoDecimalDegrees(latDMS) + ", lngDD: "
			        + DMStoDecimalDegrees(lngDMS));
			Log.v(TAG, "latDD-E6: "
			        + (int) (DMStoDecimalDegrees(latDMS) * (float) 1000000)
			        + ", lngDD-E6: "
			        + (int) (DMStoDecimalDegrees(lngDMS) * (float) 1000000));

			List<Overlay> mapOverlays = mapView.getOverlays();
			Drawable drawable = this.getResources().getDrawable(
			        R.drawable.ch6bird);
			VogelOnMapsOverlay itemizedoverlay = new VogelOnMapsOverlay(
			        drawable, this);

			GeoPoint point = new GeoPoint(
			        (int) (DMStoDecimalDegrees(latDMS) * (float) 1000000),
			        (int) (DMStoDecimalDegrees(lngDMS) * (float) 1000000));

			VogelOverlayItem overlayitem = new VogelOverlayItem(point, naam,
			        "Locatie: latDMS: " + latDMS + ", lngDMS: " + lngDMS, photo);

			itemizedoverlay.addOverlay(overlayitem);

			mapOverlays.add(itemizedoverlay);

			/*
			 * bmImg = BitmapFactory.decodeStream(is);
			 * imView.setImageBitmap(bmImg);
			 */
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public float DMStoDecimalDegrees(String dms) 
	{
		String[] parts = dms.split("/1");

		for (int i = 0; i < parts.length; i++) {
			parts[i] = parts[i].replace(" ", "");
			parts[i] = parts[i].replace(",", "");
		}

		float degrees = new Float(parts[0]);
		float seconds = new Integer(parts[1]) * 60 + new Integer(parts[2]);
		float fractionalSeconds = seconds / 3600;
		float dd = degrees + fractionalSeconds;

		return dd;
	}

	public void onLocationChanged(Location location)
	{
		int lat = (int) (location.getLatitude());
		int lng = (int) (location.getLongitude());

	}

	public void setLocation(int lat, int lng)
	{
		myMapController.setCenter(new GeoPoint(lat, lng));
	}

	public void onProviderDisabled(String arg0)
	{

	}

	public void onProviderEnabled(String arg0)
	{

	}

	public void onStatusChanged(String arg0, int arg1, Bundle arg2)
	{

	}
}


